﻿package com.cw.war.ui
{

	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	
	import net.libra.utils.Reflection;

	/**
	 * @author DanielLu
	 */
	public class AttachIcon
	{
		private var icon : MaskedSprite;

		private var cachedIcon : DisplayObject;
		private var cachedIconName : String;

		public function AttachIcon ( mc : DisplayObjectContainer )
		{
			this.icon = new MaskedSprite ();
			this.icon.x = mc.x;
			this.icon.y = mc.y;
			this.icon.setMaskBound ( 0 , 0 , mc.width , mc.height );
			mc.parent.addChildAt ( this.icon , mc.parent.getChildIndex ( mc ) );
			mc.parent.removeChild ( mc );
			this.cachedIconName = "";
		}

		/**
		 * 设置图标
		 */
		public function attachIcon ( path : String = null ) : void
		{
			if (this.cachedIconName != path)
			{
				// 去除先前的属性
				if (this.cachedIcon) this.icon.removeChild ( this.cachedIcon );

				if (path != null)
				{
					// 创建图形
					var mc : DisplayObject = Reflection.createDisplayObjectInstance ( path );
					var b : Rectangle = icon.getMaskBound ();
					// trace( mc.width , mc.height );
					mc.x = (b.width - mc.width) / 2;
					mc.y = (b.height - mc.height) / 2;
					this.icon.addChild ( mc );

					// 复制新属性
					this.cachedIcon = mc;
					this.cachedIconName = path;
				}
				else
				{
					this.cachedIcon = null;
					this.cachedIconName = null;
				}
			}
		}

		public function clear () : void
		{
			if (this.cachedIcon) this.icon.removeChild ( this.cachedIcon );
			this.cachedIcon = null;
			this.cachedIconName = null;
		}

		public function getContainer () : Sprite
		{
			return this.icon;
		}
	}
}
